package main

import (
	"fmt"
	"github/lcj/moudles_test/util"
	"io"
	"net"
	"strconv"
	"sync"
	"time"
)

type Server struct {
	Ip   string
	Port int
	//在线用户map
	OnlineMap map[string]*User
	mapLock   sync.RWMutex
	//广播channel
	Message chan string
}

func creatServer(ip string, port int) *Server {
	server := &Server{
		Ip:        ip,
		Port:      port,
		OnlineMap: make(map[string]*User),
		Message:   make(chan string),
	}
	return server
}

func (this *Server) Start() {
	listener, err := net.Listen("tcp", this.Ip+":"+strconv.Itoa(this.Port))
	if err != nil {
		fmt.Println("net.Listen err:", err)
		return
	}
	defer listener.Close()

	fmt.Println("开始监听用户消息...")
	util.PushNotification("提示", "开始监听用户消息...", "lcj.jpg")
	go this.ListenMessage()

	for {
		conn, err := listener.Accept()
		if err != nil {
			fmt.Println("listener.Accept err:", err)
			continue
		}

		go this.HandlerConnection(conn)
	}

}

func (this *Server) HandlerConnection(conn net.Conn) {
	//将用户加入onlineMap
	user := CreateUser(conn, this)

	//处理用户在线
	user.Online()

	//监听用户是否活跃的channel
	isLive := make(chan bool)

	//开启一个协程死循环读取套接字数据
	go func() {
		buf := make([]byte, 4096)
		for {
			n, err := conn.Read(buf)
			if n == 0 {
				user.Offline()
				return
			}

			if err != nil && err != io.EOF {
				fmt.Println("Conn read err:", err)
				return
			}

			//提取用户消息
			msg := string(buf[:n-1])
			user.DoMessage(msg)

			//用户任意消息代表用户活跃
			isLive <- true
		}
	}()
	for {
		select {
		case <-isLive:
			//用户活跃，触发重置定时器
		case <-time.After(time.Hour * 7):
			//发送离线消息
			user.SendMsg("长时间无操作，已退出登录")

			//销毁用户资源
			close(user.Channel)
			conn.Close()
			return
		}

	}
}

// BroadCast 广播，发送消息到Channel
func (this *Server) BroadCast(user *User, msg string) {
	sendMsg := "[" + user.Ip + "] " + user.Name + ": " + msg
	this.Message <- sendMsg
}

// ListenMessage 监听广播Channel，发送到客户端
func (this *Server) ListenMessage() {
	for {
		msg := <-this.Message
		this.mapLock.Lock()
		for _, cli := range this.OnlineMap {
			cli.Channel <- msg
		}
		this.mapLock.Unlock()
	}
}
